package Chapter06;

/**
 * 使用线程局部变量实现线程同步
 * ThreadLocal和同步机制都是为了解决线程中相同变量的访问冲突的问题,前者采用空间换时间的方式,
 * 后者采用以时间换空间的方式。
 * Created by a on 2017/6/12.
 */
public class Test37 {
    public static void main(String[] args) {
        Bank3 bank3 = new Bank3();
        Transfer3 transfer3 = new Transfer3(bank3);
        Thread thread = new Thread(transfer3);
        Thread thread1 = new Thread(transfer3);
        thread.start();
        thread1.start();
    }

}

class Bank3 {
    private static ThreadLocal<Integer> account = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 100;
        }
    };

    public void deposit(int money){
        account.set(account.get()+money);
    }
    public int getAccount(){
        return account.get();
    }
}

class Transfer3 implements Runnable{

    private Bank3 bank;

    public Transfer3(Bank3 bank) {
        this.bank = bank;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10;i++){
            bank.deposit(10);
            System.out.println("账户的余额是:"+bank.getAccount());
        }
    }
}